package sdfinal;

import sdfinal.ListServidor;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.ArrayList;

public class ServidorPrincipal extends Thread {

	@Override
	public void run() {
		try {
			ServerSocket welcomeSocket = new ServerSocket(11111);
			while (true) {
				Socket connectionSocket = welcomeSocket.accept();
				new Thread(new ThreadBuscaServidores(connectionSocket)).start();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private class ThreadBuscaServidores implements Runnable {

		private Socket connectionSocket;

		public ThreadBuscaServidores(Socket connectionSocket) {
			this.connectionSocket = connectionSocket;
		}

		@Override
		public void run() {
			try {
				// recebe requisicao do cliente
				String arquivo;
				BufferedReader inFromClient = new BufferedReader(new InputStreamReader(
						connectionSocket.getInputStream()));
				DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
				arquivo = inFromClient.readLine();

				// enviar pergunta aos servidores de arquivo
				InetAddress addr = InetAddress.getByName("239.0.0.1");
				DatagramSocket socket = new DatagramSocket();
				byte[] data = arquivo.getBytes();
				DatagramPacket pkg = new DatagramPacket(data, data.length, addr, 6000);
				socket.send(pkg);

				// receber as respostas dos servidores
				ArrayList<ListServidor> servidores = new ArrayList<ListServidor>();
				DatagramSocket socketRecebe = new DatagramSocket(7000);
				socketRecebe.setSoTimeout(10000);
				while (true) {
					try {
						byte rec[] = new byte[256];
						DatagramPacket packet = new DatagramPacket(rec, rec.length);
						socketRecebe.receive(packet);
						String[] resposta = new String(packet.getData(), 0, packet.getLength()).split(",");
						servidores.add(new ListServidor(resposta[0], Integer.parseInt(resposta[1])));

					} catch (SocketTimeoutException s) {
						socketRecebe.close();
						break;
					}
				}

				// envia resposta para o cliente
				String resposta = "";
				for (int i = 0; i < servidores.size(); i++)
					resposta += servidores.get(i).nome + "," + servidores.get(i).porta + "\r\n";

				outToClient.writeBytes(resposta);
				outToClient.close();

				connectionSocket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}